import os
import fnmatch

import Image

import imageMatcher
reload(imageMatcher)
import replacer
reload(replacer)

from imageMatcher import ImageMatcher



class ImageProcessor:

        def __init__(self, filename):
                self.filename = filename
                self.replacer = replacer.Replacer()

        def run(self, directories, box, rows, columns, \
                basicCheckingUnitAsPrecentage, maximumDifference, \
                fileType='png'):
                
                image = Image.open(self.filename)
                images = openImages(directories, fileType)
                            
                self.replacer.setMatcher(\
                        ImageMatcher(images, basicCheckingUnitAsPrecentage, \
                                     maximumDifference))      
                self.replacer.setImage(image)
                self.replacer.setBox(box)
                self.replacer.setGridDimentions((rows, columns))
       
                return self.replacer.replaceBox()

        def save(self):               
                self.replacer.getCurrentImage().save(self.filename)
        def saveAs(self,filename):
                self.replacer.getCurrentImage().save(filename)
        def undo(self):
               return self.replacer.undo()        
        def redo(self):
                return self.replacer.redo()                

                       
def openImages(directories, fileType):
  images = []
  
  for dir in directories:
    for file in os.listdir(dir):
        if (fnmatch.fnmatch(file, "*." + fileType)):
              fullname = dir+"\\"+file
              image = Image.open(fullname)
              images.append(image)
              
  return images